package org.sparkle.register;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sparkle.scanner.AnnotationScanner;

@SuppressWarnings("rawtypes")
public class RegisterFactory{
	
	private Map<String,AbstractRegister> registers;
	private Map<String,RegisterObj> instances;

	private static RegisterFactory instance;
	protected final static Logger log=LoggerFactory.getLogger(RegisterFactory.class);
	
	private RegisterFactory() {
	}

	@SuppressWarnings("unchecked")
	public static RegisterFactory getInstance(){
		if(instance==null){
			
			instance=new RegisterFactory();
			try {
				
				 AnnotationScanner annotationScanner = new AnnotationScanner();
				
				
				List<Class> annotated=annotationScanner.getListByAnnotation(Register.class);
				
				for(Class c: annotated){

					try {						
						
						Register ann=(Register) c.getAnnotation(Register.class);
						
						instance.getRegisters().put(ann.name(),(AbstractRegister)c.newInstance());
						
					} catch (InstantiationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
				}
				
				for(AbstractRegister as: instance.getRegisters().values()){
					as.populateInstances(annotationScanner, instance.getInstances());
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		}
		return instance;
	}

	public Map<String,AbstractRegister> getRegisters() {
		if(registers==null)
			registers=new HashMap<String,AbstractRegister>();
		return registers;
	}
	
	public AbstractRegister getRegisterByName(String name){
		return getRegisters().get(name);
	}

	public Map<String,RegisterObj> getInstances() {
		if(instances==null)
			instances=new HashMap<String,RegisterObj>();
		return instances;
	}
	
	public static void init(){
		getInstance();
	}
}
